package com.thinkgem.jeesite.common.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.modules.ems.entity.Order;

public class ZxingUtils {
	
//	public static void zxingQrcode(String iccid) throws IOException{
//		String text="http://wl.chuangmobile.com/ssmjee/app/card/info?iccid="+iccid;
//		int width=100;
//		int height=100;
//		String format="png";
//		Hashtable hints=new Hashtable();
//		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//		hints.put(EncodeHintType.MARGIN, 2);
//		try {
//		BitMatrix bitMatrix=new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
//		 Path file=new File("D:/cardtest/"+iccid+".png").toPath();
//		MatrixToImageWriter.writeToPath(bitMatrix, format, file);
//		
//		System.out.println("物联网卡生成二维码"+iccid);
//		} catch (WriterException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//		}
//	}
//	public static void main(String[] args) throws IOException {
//		String text="www.baidu.com";
//		int width=100;
//		int height=100;
//		String format="png";
//		Hashtable hints=new Hashtable();
//		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//		hints.put(EncodeHintType.MARGIN, 2);
//		try {
//		BitMatrix bitMatrix=new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
//		 Path file=new File("D:/new.png").toPath();
//		MatrixToImageWriter.writeToPath(bitMatrix, format, file);
//		} catch (WriterException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//		}
//		/*解析二维码：
//		public static void main(String[] args) throws NotFoundException {
//		MultiFormatReader formatReader=new MultiFormatReader();
//		File file =new File("D:/new.png");
//		BufferedImage image=null;
//		try {
//		image = ImageIO.read(file);
//		} catch (IOException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//		}
//		BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//		Hashtable hints=new Hashtable();
//		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//		Result result=formatReader.decode(binaryBitmap,hints);
//		System.err.println("解析结果："+result.toString());
//		System.out.println(result.getBarcodeFormat());
//		System.out.println(result.getText());
//		}*/
//	}
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	 // LOGO宽度  
    private static final int WIDTH = 400;  
    // LOGO高度  
    private static final int HEIGHT = 440; 
	/**
	 * 把生成的二维码存入到图片中
	 * @param matrix zxing包下的二维码类
	 * @return
	 */
	public static BufferedImage toBufferedImage(BitMatrix matrix) {
	 int width = matrix.getWidth();
	 int height = matrix.getHeight();
	 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	 for (int x = 0; x < width; x++) {
	  for (int y = 0; y < height; y++) {
	   image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
	  }
	 }
	 return image;
	}
	/**
	 * 生成二维码并写入文件
	 * @param content 扫描二维码的内容
	 * @param format 图片格式 jpg
	 * @param file  文件
	 * @throws Exception
	 */
	public static void writeToFile(String content, String format, File file)
	  throws Exception {
	 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
	 @SuppressWarnings("rawtypes")
	 Map hints = new HashMap();
	 //设置UTF-8， 防止中文乱码
	 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
	 //设置二维码四周白色区域的大小
	 hints.put(EncodeHintType.MARGIN,1);
	 //设置二维码的容错性
	 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
	 //画二维码
	 BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
	 BufferedImage image = toBufferedImage(bitMatrix);
	 if (!ImageIO.write(image, format, file)) {
	  throw new IOException("Could not write an image of format " + format + " to " + file);
	 }
	}

	//第三步、把文字写入二维码图片中：

	/**
	 * 给二维码图片加上文字
	 * @param pressText 文字
	 * @param qrFile  二维码文件
	 * @param fontStyle
	 * @param color
	 * @param fontSize
	 */
	public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
	 pressText = new String(pressText.getBytes(), "utf-8");
	 Image src = ImageIO.read(qrFile);
	 int imageW = src.getWidth(null);
	 int imageH = src.getHeight(null);
	 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
	 /*Graphics g = image.createGraphics();
	 g.drawImage(src, 0, 0, imageW, imageH, null);
	 //设置画笔的颜色
	 g.setColor(color);
	 //设置字体
	 Font font = new Font("宋体", fontStyle, fontSize);
	 FontMetrics metrics = g.getFontMetrics(font);
	 //文字在图片中的坐标 这里设置在中间
	 int startX = (WIDTH - metrics.stringWidth(pressText))/12 ;
	 int startY = HEIGHT/2 - 20;
	 g.setFont(font);
	 g.drawString(pressText, startX, startY);*/
	 
	 
	 /*int startX1 = (WIDTH - metrics.stringWidth(pressText))/20 ;
	 int startY1 = HEIGHT/18;
	 Font font1 = new Font("黑体", 200, 15);
	 g.setFont(font1);
	 g.drawString("流量卡查询续费扫描二维码", startX1, startY1);
	 
	 int startX2 = (WIDTH - metrics.stringWidth(pressText))/40 ;
	 int startY2 = HEIGHT/2 - 8;
	 Font font2 = new Font("黑体", 200, 14);
	 g.setFont(font2);
	 g.drawString("贴于终端后盖内平整处以便使用", startX2, startY2);
	 g.dispose();*/
	 FileOutputStream out = new FileOutputStream(qrFile);
	 ImageIO.write(image, "JPEG", out);
	 
	 out.close();
	 System.out.println("image press success");
	}

	public static void zxingQrcode(HttpServletRequest request,Order order/*, List<FileBean> files*/) throws Exception {
		
		String orderNo = order.getOrderNo();
		String money = String.valueOf(order.getMoney());
		String domainName = Global.getConfig("domainName");
		if(StringUtils.isBlank(domainName))
		{
			domainName = "http://www.sdsxdw.com";
		}
		
		// 生产
		// String text= domainName + "/weixin/getCode?url=${ctx}/weixin/pay?oid=" + orderNo + "!p=" + money;
		// 二维码中不再提现金额，避免篡改，而修改为从订单拼接
		String text= domainName + "/weixin/getCode?ono=" + orderNo/* + "!p=" + money*/;
		
		// 测试
		// String text= domainName + "/weixin/getCode?url=" + domainName + "/weixin/pay?oid=" + orderNo + "!p=0.01";
		
		int width=210;
		int height=210;
		String format="png";
		Hashtable hints=new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		hints.put(EncodeHintType.MARGIN, 2);
		// String qrcodePath = request.getSession().getServletContext().getRealPath(Global.getConfig("payQRCodePath"));
		String qrcodePath = Global.getConfig("payQRCodePath");
		File filePath = new File(qrcodePath);
		if(!filePath.exists())
		{
			filePath.mkdirs();
		}
		// FileReader read = new FileReader(new File(qrcodePath));
		try {
		BitMatrix bitMatrix=new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
		Path file=new File(qrcodePath+"/"+orderNo+".png").toPath();
		MatrixToImageWriter.writeToPath(bitMatrix, format, file);
		/*File file1 = new File(qrcodePath+"/"+orderSn+".png");
		pressText(orderSn, file1 , 400, Color.BLACK, 16);*/
		System.out.println("订单支付生成二维码"+orderNo);
		/*FileBean fileBean = new FileBean();
		fileBean.setFileName(iccid+".png");
		fileBean.setFilePath(qrcodePath);
		files.add(fileBean);
		ZipUtils.toZip(request,files);*/
		} catch (WriterException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
		
	}
}
